package Arrays;

/**
 * 作者:hfj
 * 功能:21.合并两个有序的链表
 * 日期: 2025/10/17 20:45
 */
public class MergeTwoList {
    public static void main(String[] args) {

    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next;}

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        //合并成新链表和一个临时节点
        ListNode pre = new ListNode(-1), temp =pre;

        //合并两个有序链表
        while (list1 != null && list2 != null){
            if (list1.val <= list2.val){
                temp.next = new ListNode(list1.val);
                temp = temp.next;
                list1 = list1.next;
            }else{
                temp.next = new ListNode(list2.val);
                temp = temp.next;
                list2 = list2.next;
            }
        }
        //合并完剩下的链表
        while (list1 != null){
            temp.next =new ListNode(list1.val);
            temp = temp.next;
            list1 = list1.next;
        }
        //合并完剩下的链表
        while (list2 != null){
            temp.next = new ListNode(list2.val);
            temp = temp.next;
            list2 = list2.next;
        }
        return pre.next;
    }
}

